package com.neo.service;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.neo.entity.errorMessage.RespErrorCode;
import com.neo.util.ErrorFileUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.neo.util.DjsStringUtil;

@Service
public class DjsUserFileService {

    protected static Logger logger= LoggerFactory.getLogger(DjsUserFileService.class); 
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    String errcode = null;

    public Map<String, String> readResFile(List<String> list) throws Exception {
        int res_f = 0;
        int res_s = 0;
        int res_n = 0;
        Map<String, String> result = new HashMap<>();
        List<String> errData = new ArrayList<>();
        for (String str : list) {
            String flag = DjsStringUtil.cutByGBK(str, 39, 1);
            String cardnbr = null;
            String idno = null;
            switch (flag) {
                case "F":
                    errcode = DjsStringUtil.cutByGBK(str, 40, 3);// pass
                    StringBuffer data = new StringBuffer("失败原因：").append(RespErrorCode.getName("APPZX" + errcode)).append("，原数据为=========>").append(str);
                    errData.add(data.toString());
                    System.out.println();
                    res_f++;
                    break;
                case "S":
                    cardnbr = DjsStringUtil.cutByGBK(str, 0, 19);// todo
                    idno = DjsStringUtil.cutByGBK(str, 19, 18);
                    updateUserCardnbr(idno, cardnbr);
                    res_s++;
                    break;
                case "N":
                    cardnbr = DjsStringUtil.cutByGBK(str, 0, 19);// 幂等
                    idno = DjsStringUtil.cutByGBK(str, 19, 18);
                    updateUserCardnbr(idno, cardnbr);
                    res_n++;
                    break;
                default:
                    break;
            }
        }

        if (errData.size() > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            result = ErrorFileUtil.handle(errData, "APPZXErrorDataFile" + simpleDateFormat.format(new Date()) + "00" + res_f + res_n + res_s);
        }
        logger.info("失败F条数"+res_f + "");
        logger.info("成功S条数"+res_s + "");
        logger.info("已开户N条数"+res_n + "");
        logger.info("处理总数"+list.size() + "");
        
        
        result.put("失败F条数", res_f + "");
        result.put("成功S条数", res_s + "");
        result.put("已开户N条数", res_n + "");
        result.put("处理总数", list.size() + "");
        return result;
    }

    private void updateUserCardnbr(String idno, String cardnbr) {
        String sql = "UPDATE jx_account_info  SET  ACCOUNT_ID  =?  WHERE ID_NO =? ";
        int i = jdbcTemplate.update(sql, cardnbr, idno);
    }

    public String generalFile(String batch) throws Exception {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM inv_user a where LENGTH(identity_no)=18 and REGISTER_CHANNEL_NO =1  ", new Object[]{});
        List<String> resList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
        	logger.info("=="+i);
        	if(i==183) {
            	logger.info("=="+i);
        	}
			Map map = list.get(i);
            String idno = (String) map.get("IDENTITY_NO");
            String name = (String) map.get("NAME");
            String mophone = (String) map.get("MOBILE");
            String email = (String) map.get("EMAIL_ADDRESS");

            if (!checkIDNO(idno)) {
                continue;
            }
            String sex = getSexFromIDNO(idno);

            if (!checkName(name)) {
                continue;
            }
            if (!checkPhone(mophone)) {
                continue;
            }
            email = getEmail(email);

            name = DjsStringUtil.trimBlank(name);

            String res = "" + idno + "01" + DjsStringUtil.fillBlank(name, 60) // 中文姓名
                    + DjsStringUtil.fillBlank(sex, 1) // 性别
                    + DjsStringUtil.fillBlank(mophone, 12) // 手机号码
                    + "0" // 账户类型
                    + DjsStringUtil.fillBlank(email, 40) // E-mail地址
                    + DjsStringUtil.fillBlank(getAppid() + "", 60) // 请求方用户ID
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 9)// 营业执照编号
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 30)// 税务登记号
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 20)// 渠道推荐码
                    + "2" // 账户类型
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 2)// 基金公司代码
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 100)// 请求方保留信息
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 42)// 对公账户号
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 18)// 营业执照编号
                    + DjsStringUtil.fillBlank(DjsStringUtil.BLANK, 17)// 保留域
                    ;
            System.out.println(res);

            byte[] bs = res.getBytes("GBK");
            System.out.println(bs.length);
            if (bs.length != 433) {
                System.out.println("生成出错");
            }
            ;
            resList.add(res);
        }
        System.out.println("生成文件行数" + resList.size());

        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String strDate = dateFormater.format(date);
        String fileName = DjsStringUtil.FILE_PATH + DjsStringUtil.BANKID + "-APPZX" + DjsStringUtil.PRODUCT + "-"
                + batch + "-" + strDate;
        DjsStringUtil.writeStringToFile(resList, batch, fileName);

        return fileName;
    }

    private String getEmail(String email) {
        if (email == null) {
            return DjsStringUtil.BLANK;
        }
        if (email.length() > 40) {
            email = email.substring(0, 40);
        }
        return email;
    }

    private long getAppid() {
        java.util.Random r = new java.util.Random();
        return System.currentTimeMillis() + r.nextInt(99999);
    }

    private boolean checkPhone(String name) throws ParseException {
        if (name == null || name.length() > 60 || name.length() == 0) {
            return false;
        }
        return true;
    }

    private boolean checkName(String name) throws ParseException {
        if (name == null || name.length() > 60 || name.length() == 0) {
            return false;
        }
        return true;
    }

    private boolean checkIDNO(String idno) throws ParseException {
        if (idno == null || idno.length() != 18) {
            return false;
        }
        int year = Integer.parseInt(idno.substring(6, 10));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date update = sdf.parse(String.valueOf(year + 18) + idno.substring(10, 14));
        Date today = new Date();
        if (!today.after(update)) {
            System.out.println("error id" + idno);
            return false;
        }

        return true;
    }

    private String getSexFromIDNO(String idno) throws ParseException {
        String s = idno.substring(16, 17);
        if (s.equals("1") || s.equals("3") || s.equals("5") || s.equals("7") || s.equals("9")) {
            s = "1";//男
        } else {
            s = "2";//女
        }
        return s;
    }

    public static String formatString(String in, int len) {
        String s = "123中国123";
        return String.format("%1$-" + len + "s", in);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "1304011976041103x7";
        System.out.println(s.substring(16, 17));
    }
}